package cn.com.generaldata.os.service.indicator_evaluation.sustainable_development;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.Exps;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.vo.IndicatorAccountVO;

/**
 * 可持续发展综合指标计算类.
 */
public class SustainableDevelopmentCalculateService extends IndicatorEvaluationCalculateService {

	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double result = null;
		if (indicator.getSection() == Constants.INDICATOR_LEVEL_PROVINCE) {
			result = calculateProvinceResult(indicator, indicatorAccountVO);
		} else if (indicator.getSection() == Constants.INDICATOR_LEVEL_CITY) {
			// 市指标没确定先保留
		}
		return result;
	}

	/**
	 * 获得可持续发展综合指标引用的相关指标.
	 * 
	 * @return
	 */
	private List<IndicatorEvaluation> getReferenceIndicators() {
		Cnd cnd = Cnd.where(Exps.like("name", "标准化", false));
		return indicatorSystemDao.query(IndicatorEvaluation.class, cnd);
	}

	/**
	 * 计算江苏省进出口总额增长率评估指标计算类.
	 * 
	 * @param indicator
	 * @param indicatorAccountVO
	 * @return
	 */
	private Double calculateProvinceResult(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		List<IndicatorEvaluation> references = getReferenceIndicators();
		Double result = 0d;
		for (IndicatorEvaluation reference : references) {
			Double indicatorVal = getIndicatorVal(indicatorAccountVO, indicatorAccountVO.getYear(), reference);

			Double weighted = getIndicatorValWeighted(indicatorAccountVO, indicatorAccountVO.getYear(), reference);

			result += indicatorVal * weighted;
		}

		return result;
	}

	/**
	 * 获得指标的权重,先从录入指标中取，没有的话取默认值.
	 * 
	 * @param indicatorAccountVO
	 * @param year
	 * @param indicator
	 * @return
	 */
	private Double getIndicatorValWeighted(IndicatorAccountVO indicatorAccountVO, int year,
			IndicatorEvaluation indicator) {
		String weightIndicatorName = indicator.getName() + "权重";
		Double weight = getInputOrAccountingIndicatorValue(indicatorAccountVO, year, weightIndicatorName);
		return weight == null ? 1d : indicator.getWeight();
	}

	private Double getIndicatorVal(IndicatorAccountVO indicatorAccountVO, int year, IndicatorEvaluation indicator) {

		Criteria cri = getIndicatorDataCri(indicatorAccountVO, year, indicator.getId());
		Double result = getEvaluationIndicatorValue(cri);

		return result == null ? 0d : result;
	}

}
